package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.GoodsListOrderRecycleAdapter;
import com.weixin.paleituo.annotation.OrderStatusType;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.OrderCreatedBean;
import com.weixin.paleituo.bean.OrderDetailsBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.TipsDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 订单详情界面
 * 包含四种状态：代付款、待收货、已完成、已取消 {@link OrderStatusType}
 *
 * @author fengzhen
 * @version v1.0, 2018/4/6
 */
public class OrderDetailsActivity extends BasePersonActivity {

    @BindView(R.id.tv_wait_activity_order_details)
    TextView mTvWaitActivityOrderDetails;
    @BindView(R.id.tv_pricing_activity_order_details)
    TextView mTvPricingActivityOrderDetails;
    @BindView(R.id.tv_remaining_time_activity_order_details)
    TextView mTvRemainingTimeActivityOrderDetails;
    @BindView(R.id.tv_need_pay_activity_order_details)
    TextView mTvNeedPayActivityOrderDetails;
    @BindView(R.id.img_go_next)
    ImageView mImgGoNext;
    @BindView(R.id.tv_user_layout_order_address)
    TextView mTvUserLayoutOrderAddress;
    @BindView(R.id.tv_tel_layout_order_address)
    TextView mTvTelLayoutOrderAddress;
    @BindView(R.id.img_default_layout_order_address)
    ImageView mImgDefaultLayoutOrderAddress;
    @BindView(R.id.linear_user_info)
    LinearLayout mLinearUserInfo;
    @BindView(R.id.tv_address_layout_order_address)
    TextView mTvAddressLayoutOrderAddress;
    @BindView(R.id.relative_layout_order_address)
    RelativeLayout mRelativeLayoutOrderAddress;
    @BindView(R.id.tv_store_activity_order_details)
    TextView mTvStoreActivityOrderDetails;
    @BindView(R.id.recycler_activity_order_details)
    RecyclerView mRecyclerActivityOrderDetails;
    @BindView(R.id.linear_goods_activity_order_details)
    LinearLayout mLinearGoodsActivityOrderDetails;
    @BindView(R.id.tv_number_activity_order_details)
    TextView mTvNumberActivityOrderDetails;
    @BindView(R.id.tv_date_activity_order_details)
    TextView mTvDateActivityOrderDetails;
    @BindView(R.id.tv_invoice_type_activity_order_details)
    TextView mTvInvoiceTypeActivityOrderDetails;
    @BindView(R.id.tv_invoice_head_activity_order_details)
    TextView mTvInvoiceHeadActivityOrderDetails;
    @BindView(R.id.tv_custom_info_activity_order_details)
    TextView mTvCustomInfoActivityOrderDetails;
    @BindView(R.id.linear_custom_activity_order_details)
    LinearLayout mLinearCustomActivityOrderDetails;
    @BindView(R.id.tv_goods_money_activity_order_details)
    TextView mTvGoodsMmoneyActivityOrderDetails;
    @BindView(R.id.tv_express_activity_order_details)
    TextView mTvExpressActivityOrderDetails;
    @BindView(R.id.tv_deduction_activity_order_details)
    TextView mTvDeductionActivityOrderDetails;
    @BindView(R.id.tv_pay_activity_order_details)
    TextView mTvPayActivityOrderDetails;
    @BindView(R.id.btn_black_activity_order_details)
    Button mBtnCancelActivityOrderDetails;
    @BindView(R.id.btn_delete_activity_order_details)
    Button mBtnDeletelActivityOrderDetails;
    @BindView(R.id.btn_green_activity_order_details)
    Button mBtnPayActivityOrderDetails;
    @BindView(R.id.linear_handle_activity_order_details)
    LinearLayout mLinearHandleActivityOrderDetails;
    @BindView(R.id.linear_store_activity_order_details)
    LinearLayout mLinearStoreActivityOrderDetails;
    @BindView(R.id.tv_pay_type_activity_order_details)
    TextView mTvPayTypeActivityOrderDetails;
    @BindView(R.id.tv_pay_date_activity_order_details)
    TextView mTvPayDateActivityOrderDetails;
    @BindView(R.id.tab_pay_activity_order_details)
    TableLayout mTabPayActivityOrderDetails;
    @BindView(R.id.line_pay_activity_order_details)
    View mLinePayActivityOrderDetails;
    @BindView(R.id.tab_invoice_head)
    TableRow mTabInvoiceHead;
    @BindView(R.id.tv_text_pay_activity_order_details)
    TextView mTvTextPayActivityOrderDetaild;
    @BindView(R.id.relative_express_activity_order_details)
    RelativeLayout mRelativeExpressActivityOrderDetaild;
    @BindView(R.id.relative_coupons_info_activity_order_details)
    RelativeLayout mRelativeCouponsInfoActivityOrderDetaild;
    @BindView(R.id.tv_express_curr_activity_order_details)
    TextView mTvExpressCurrActivityOrderDetaild;
    @BindView(R.id.tv_express_date_activity_order_details)
    TextView mTvExpressDateActivityOrderDetaild;
    @BindView(R.id.line1)
    View mLine1;
    @BindView(R.id.line_custom)
    View mLineCustom;

    private DecimalFormat format = new DecimalFormat("#0.00");

    private LoadingPagerHead mLoadingPagerHead;
    private TipsDialog mCancelDialog;
    private TipsDialog mGotGoodsDialog;
    private TipsDialog mDeleteDialog;

    private int mOrderId;
    private String mDetailId;
    private OrderDetailsBean mOrderDetail;
    private Disposable mTimerDisposable;

    /**
     * 跳转订单详情界面，传入orderId，订单状态根据数据返回处理不同UI逻辑
     *
     * @param orderId  订单Id
     * @param detailId 当查询的订单状态不为待付款（orderStatus=1）或者已取消（orderStatus=7）时，将详情订单id传过来
     */
    public static Intent call2OrderDetailsActivity(Context context, int orderId, String detailId) {
        Intent intent = new Intent(context, OrderDetailsActivity.class);
        intent.putExtra(Contans.INTENT_DATA, orderId);
        intent.putExtra(Contans.INTENT_EXTRA, detailId);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {
                onBackPressed();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(OrderDetailsActivity.this, R.layout.activity_order_details);
            }

            @Override
            protected void reLoading() {
                getOrderInfo();
            }
        };
        return mLoadingPagerHead;
    }

    @Override
    protected void initView() {
        super.initView();
        mOrderId = getIntent().getIntExtra(Contans.INTENT_DATA, 0);
        mDetailId = getIntent().getStringExtra(Contans.INTENT_EXTRA);
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("订单详情");
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderInfo();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (mTimerDisposable != null && !mTimerDisposable.isDisposed()) {
            mTimerDisposable.dispose();
        }
        super.onDestroy();
    }

    @OnClick({R.id.btn_black_activity_order_details, R.id.btn_green_activity_order_details,
            R.id.linear_store_activity_order_details, R.id.btn_delete_activity_order_details,
            R.id.relative_express_activity_order_details})
    public void onClickM(View view) {
        switch (view.getId()) {
            /**
             * 黑色框按钮 取消订单 确认收货 删除订单
             */
            case R.id.btn_black_activity_order_details:
                if (mOrderDetail.getOrderStatus() == OrderStatusType.WAIT_PAY) {
                    showCancelDialog();
                } else if (mOrderDetail.getOrderStatus() == OrderStatusType.CANCEL) {
                    showDeleteDialog(1);
                } else {
                    switch (mOrderDetail.getStoreList().get(0).getOrderStatus()) {
                        case OrderStatusType.WAIT_PAY:
                            showCancelDialog();
                            break;
                        case OrderStatusType.WAIT_SHIPMENTS:
                        case OrderStatusType.WAIT_RECEIVING:
                            showGotGoodsDialog();
                            break;
                        case OrderStatusType.FINISH:
                            showDeleteDialog(2);
                            break;
                        case OrderStatusType.CANCEL:
                            showDeleteDialog(1);
                            break;
                    }
                }
                break;

            /**
             * 绿色框按钮 去支付 再次购买
             */
            case R.id.btn_green_activity_order_details:
                switch (mOrderDetail.getOrderStatus()) {
                    case OrderStatusType.WAIT_PAY:
                        gotoPayOrder();
                        break;
                    case OrderStatusType.CANCEL:
                        buyAgain();
                        break;
                }
                break;

            /**
             * 跳转物流地址界面
             */
            case R.id.relative_express_activity_order_details:
                ExpressActivity.startActivity(this, mOrderDetail.getStoreList().get(0).getOrderDetailaId());
                break;

            /**
             * 删除订单  已取消界面
             */
            case R.id.btn_delete_activity_order_details:
                if (OrderStatusType.CANCEL == mOrderDetail.getOrderStatus()) {
                    showDeleteDialog(1);
                }
                break;

            /**
             * 去店铺
             */
            case R.id.linear_store_activity_order_details:
                // 当前版本不做
//                int storeId = mOrderDetail.getStoreList().get(0).getStoreId();
//                if (storeId > 0) {
//                    GoodsStoreActivity.startActivity(this, storeId);
//                }
                break;
        }
    }

    /**
     * 确认收货
     */
    private void showGotGoodsDialog() {
        if (mGotGoodsDialog == null) {
            mGotGoodsDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mGotGoodsDialog.dismiss();
                        }
                    })
                    .setContentView("您是否已收到该订单商品？")
                    .setLeftButton("未收货", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mGotGoodsDialog.dismiss();
                        }
                    })
                    .setRightButton("已收货", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mGotGoodsDialog.dismiss();
                            gotGoods();
                        }
                    })
                    .build();
        }
        mGotGoodsDialog.show();
    }

    /**
     * 删除订单
     *
     * @param sign 已取消订单传1，已完成订单传2
     */
    private void showDeleteDialog(final int sign) {
        if (mDeleteDialog == null) {
            mDeleteDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mDeleteDialog.dismiss();
                        }
                    })
                    .setContentView("确定删除此订单？")
                    .setLeftButton("再想想", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDeleteDialog.dismiss();
                        }
                    })
                    .setRightButton("确定删除", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDeleteDialog.dismiss();
                            deleteOrder(sign);
                        }
                    })
                    .build();
        }
        mDeleteDialog.show();
    }

    /**
     * 再次购买
     */
    private void buyAgain() {
        ToastUtils.makeText("再次购买");
    }

    /**
     * 跳转收银台支付订单
     */
    private void gotoPayOrder() {
        int madeType = mOrderDetail.getMadeType();
        OrderCreatedBean orderData = new OrderCreatedBean();
        orderData.setOrderId(mOrderDetail.getId());
        if (madeType == 1) {
            // 定制订单
            orderData.setActualPrice(mOrderDetail.getTotalPrice());
            orderData.setCouponMoney(mOrderDetail.getStoreList().get(0).getCuCouponMoney());
        } else {
            orderData.setActualPrice(mOrderDetail.getActualPrice());
        }
        startActivity(CheckstandActivity.call2CheckstandActivity(this, madeType - 1, orderData));
    }

    /**
     * 删除订单
     *
     * @param sign 已取消订单传1，已完成订单传2
     */
    private void deleteOrder(int sign) {
        showLoadingDialog();
        Observable<StatusCode<Object>> cancelObservable = ApiUtils.getApi().deleteOrders(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                String.valueOf(mOrderDetail.getId()),
                String.valueOf(mOrderDetail.getStoreList().get(0).getDetailId()),
                String.valueOf(sign));
        HttpUtil.getInstance().toSubscribe(cancelObservable,
                new ProgressSubscriber<Object>(this) {
                    @Override
                    protected void _onNext(StatusCode<Object> statusCode) {
                        ToastUtils.makeText("订单删除成功");
                        dismissLoadingDialog();
                        MyOrderActivity.startActivity(OrderDetailsActivity.this, BaseApplication.getUserId(), 0);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 确认收货
     */
    private void gotGoods() {
        showLoadingDialog();
        Observable<StatusCode<Object>> cancelObservable = ApiUtils.getApi().getGoods(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                mOrderDetail.getStoreList().get(0).getDetailId());
        HttpUtil.getInstance().toSubscribe(cancelObservable,
                new ProgressSubscriber<Object>(this) {
                    @Override
                    protected void _onNext(StatusCode<Object> statusCode) {
                        dismissLoadingDialog();
                        // 跳转已完成
                        MyOrderActivity.startActivity(OrderDetailsActivity.this, BaseApplication.getUserId(), 3);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 展示取消订单弹框
     */
    private void showCancelDialog() {
        if (mCancelDialog == null) {
            mCancelDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mCancelDialog.dismiss();
                        }
                    })
                    .setContentView("确定取消此订单？")
                    .setLeftButton("再想想", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mCancelDialog.dismiss();
                        }
                    })
                    .setRightButton("确定取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mCancelDialog.dismiss();
                            cancelOrder();
                        }
                    })
                    .build();
        }
        mCancelDialog.show();
    }

    private void getOrderInfo() {
        mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
        Observable<StatusCode<OrderDetailsBean>> observable = ApiUtils.getApi().getOrderDetailsInfo(BaseApplication.getToken(), BaseApplication.getUserId(), mOrderId, mDetailId);
        HttpUtil.getInstance().toSubscribe(observable,
                new ProgressSubscriber<OrderDetailsBean>(this) {
                    @Override
                    protected void _onNext(StatusCode<OrderDetailsBean> statusCode) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                        mOrderDetail = statusCode.getData();
                        initOrderInfo();
                    }

                    @Override
                    protected void _onError(String message) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    private void initOrderInfo() {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, UIUtils.dip2px(25), 0, 0);

        // 地址信息展示
        mImgGoNext.setVisibility(View.GONE);
        mTvUserLayoutOrderAddress.setText(mOrderDetail.getUserName());
        mTvTelLayoutOrderAddress.setText(mOrderDetail.getUserPhone());
        mTvAddressLayoutOrderAddress.setText(mOrderDetail.getAddress());
        // 商铺信息展示
        OrderDetailsBean.StoreListBean store = mOrderDetail.getStoreList().get(0);
        mTvStoreActivityOrderDetails.setText(store.getStoreName());
        // 当前版本不做
        if (store.getStoreId() < 0) {
            mTvStoreActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                    ContextCompat.getDrawable(this, R.mipmap.icon_shushe_logo), null, null, null);
        } else {
            mTvStoreActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                    ContextCompat.getDrawable(this, R.mipmap.store_cart), null, null, null);
//            mTvStoreActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
//                    ContextCompat.getDrawable(this, R.mipmap.store_cart), null, ContextCompat.getDrawable(this, R.mipmap.ck), null);
        }
        // 商品列表
        mRecyclerActivityOrderDetails.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        GoodsListOrderRecycleAdapter adapter = new GoodsListOrderRecycleAdapter(this, new ArrayList(store.getGoodsList()));
        mRecyclerActivityOrderDetails.setAdapter(adapter);
        // 订单编号信息
        if (mOrderDetail.getOrderStatus() == OrderStatusType.WAIT_PAY
                || mOrderDetail.getOrderStatus() == OrderStatusType.CANCEL) {
            mTvNumberActivityOrderDetails.setText(mOrderDetail.getOrderId());
        } else {
            mTvNumberActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getOrderDetailaId());
        }
        mTvDateActivityOrderDetails.setText(mOrderDetail.getCreateTime());
        // 发票信息
        switch (mOrderDetail.getTitle()) {
            // 个人
            case 1:
                mTvInvoiceTypeActivityOrderDetails.setText("纸质发票");
                mTvInvoiceHeadActivityOrderDetails.setText("个人");
                mTabInvoiceHead.setVisibility(View.VISIBLE);
                break;
            // 单位
            case 2:
                mTvInvoiceHeadActivityOrderDetails.setText(mOrderDetail.getName());
                mTabInvoiceHead.setVisibility(View.VISIBLE);
                if (mOrderDetail.getGenre() == 2) {
                    mTvInvoiceTypeActivityOrderDetails.setText("专用发票");
                } else {
                    mTvInvoiceTypeActivityOrderDetails.setText("普通发票");
                }
                break;
            // 不开
            case 3:
                mTvInvoiceTypeActivityOrderDetails.setText("不开发票");
                mTabInvoiceHead.setVisibility(View.GONE);
                break;
        }
        // 定制信息
        if (mOrderDetail.getMadeType() == 1) {
            mLinearCustomActivityOrderDetails.setVisibility(View.VISIBLE);
            mTvCustomInfoActivityOrderDetails.setMinHeight(UIUtils.dip2px(80));
            mLineCustom.setVisibility(View.VISIBLE);
        } else {
            mLineCustom.setVisibility(View.GONE);
            mLinearCustomActivityOrderDetails.setVisibility(View.GONE);
        }
        // 商品金额
        mTvGoodsMmoneyActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getTotalPrice())));
        // 运费
        mTvExpressActivityOrderDetails.setText("+￥0.00");
        // 优惠券
        mTvDeductionActivityOrderDetails.setText(String.format(getString(R.string.string_sub_pay), format.format(mOrderDetail.getTotalCouponMoney())));

        /**
         * 如果是待支付订单、已取消订单，从外面获取状态，此两种状态存在合单的情况，就从外面获取
         */
        if (mOrderDetail.getOrderStatus() == OrderStatusType.WAIT_PAY) {
            initPayType(params);
        } else if (mOrderDetail.getOrderStatus() == OrderStatusType.CANCEL) {
            initCancelType(params);
        } else {
            switch (mOrderDetail.getStoreList().get(0).getOrderStatus()) {
                case OrderStatusType.WAIT_PAY:
                    initPayType(params);
                    break;

                /**
                 * 待发货
                 */
                case OrderStatusType.WAIT_RECEIVING:
                    initReceiveType(params);
                    break;

                case OrderStatusType.WAIT_SHIPMENTS:
                    initShipments(params);
                    break;

                case OrderStatusType.FINISH:
                case OrderStatusType.COMPLETE:
                    initFinishType(params);
                    break;

                case OrderStatusType.CANCEL:
                    initCancelType(params);
                    break;

                /**
                 * 当前版本不处理已退款订单
                 */
                case OrderStatusType.FEFUND:
                    break;

                default:
                    UIUtils.showCarToast(this, 1, "订单状态异常！");
                    onBackPressed();
                    break;
            }
        }
    }

    private void initCancelType(RelativeLayout.LayoutParams params) {
        // 更改蓝条样式
        mTvWaitActivityOrderDetails.setLayoutParams(params);
        mTvPricingActivityOrderDetails.setVisibility(View.GONE);
        mTvRemainingTimeActivityOrderDetails.setVisibility(View.GONE);
        mTvNeedPayActivityOrderDetails.setVisibility(View.GONE);
        mTvWaitActivityOrderDetails.setText("已取消");
        mBtnCancelActivityOrderDetails.setText("删除订单");
        mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
        mBtnCancelActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(this, R.mipmap.icon_cancel), null, null, null);
        mTabPayActivityOrderDetails.setVisibility(View.GONE);
        mLinePayActivityOrderDetails.setVisibility(View.GONE);
        // 付款汇总
        mTvTextPayActivityOrderDetaild.setText("实付款：");
        if (1 == mOrderDetail.getMadeType() && mOrderDetail.getActualPrice() <= 0) {
            mTvPayActivityOrderDetails.setText("待定");
        } else {
            mTvPayActivityOrderDetails.setText(String.format(
                    getString(R.string.string_pay), format.format(mOrderDetail.getActualPrice())));
        }
        mRelativeExpressActivityOrderDetaild.setVisibility(View.GONE);
        mLine1.setVisibility(View.GONE);

        if (1 == mOrderDetail.getMadeType()) {
            // 定制订单
            mTvCustomInfoActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getMsg());
            if (mOrderDetail.getTotalPrice() <= 0) {
                mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.GONE);
                mTvPayActivityOrderDetails.setText("￥待定");
                mTvGoodsMmoneyActivityOrderDetails.setText("￥待定");
            } else {
                mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
                mTvPayActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getTotalPrice())));
            }
        }

        /**
         * 下版开发再次购买
         */
//                mLinearHandleActivityOrderDetails.setVisibility(View.GONE);
        mBtnPayActivityOrderDetails.setVisibility(View.VISIBLE);
        mBtnDeletelActivityOrderDetails.setVisibility(View.GONE);
        mBtnPayActivityOrderDetails.setVisibility(View.GONE);
        mBtnPayActivityOrderDetails.setText("再次购买");
        mLinearHandleActivityOrderDetails.setVisibility(View.VISIBLE);
    }

    private void initFinishType(RelativeLayout.LayoutParams params) {
        // 更改蓝条样式
        mTvWaitActivityOrderDetails.setLayoutParams(params);
        mTvPricingActivityOrderDetails.setVisibility(View.GONE);
        mTvRemainingTimeActivityOrderDetails.setVisibility(View.GONE);
        mTvNeedPayActivityOrderDetails.setVisibility(View.GONE);
        mTvWaitActivityOrderDetails.setText("已完成");
        mBtnPayActivityOrderDetails.setVisibility(View.GONE);
        mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
        mBtnCancelActivityOrderDetails.setText("删除订单");
        mBtnCancelActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(this, R.mipmap.icon_complete), null, null, null);
        mTabPayActivityOrderDetails.setVisibility(View.VISIBLE);
        // 支付方式
        mLinePayActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvPayTypeActivityOrderDetails.setText(mOrderDetail.getPayType() == 1 ? "支付宝支付" : "微信支付");
        mTvPayDateActivityOrderDetails.setText(mOrderDetail.getPayTime().split(" ")[0]);
        // 付款汇总
        mTvTextPayActivityOrderDetaild.setText("实付款：");
        mTvPayActivityOrderDetails.setText(String.format(
                getString(R.string.string_pay), format.format(mOrderDetail.getActualPrice())));
        // 物流信息
        mRelativeExpressActivityOrderDetaild.setVisibility(View.VISIBLE);
        mTvExpressDateActivityOrderDetaild.setVisibility(View.GONE);
        if (TextUtils.isEmpty(mOrderDetail.getAcceptStation())) {
            mTvExpressCurrActivityOrderDetaild.setText("感谢您在舒社购物，欢迎您再次光临！");
        } else {
            mTvExpressCurrActivityOrderDetaild.setText(mOrderDetail.getAcceptStation());
        }
        mLine1.setVisibility(View.VISIBLE);
        mBtnDeletelActivityOrderDetails.setVisibility(View.GONE);
        mLinearHandleActivityOrderDetails.setVisibility(View.VISIBLE);
        if (1 == mOrderDetail.getMadeType()) {
            // 定制订单
            mTvCustomInfoActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getMsg());
            mLinearCustomActivityOrderDetails.setVisibility(View.VISIBLE);
        } else {
            mLinearCustomActivityOrderDetails.setVisibility(View.GONE);
        }
    }

    private void initShipments(RelativeLayout.LayoutParams params) {
        // 更改蓝条样式
        mTvWaitActivityOrderDetails.setLayoutParams(params);
        mTvPricingActivityOrderDetails.setVisibility(View.GONE);
        mTvRemainingTimeActivityOrderDetails.setVisibility(View.GONE);
        mTvNeedPayActivityOrderDetails.setVisibility(View.GONE);
        mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setText("等待收货");
        mBtnPayActivityOrderDetails.setVisibility(View.GONE);
        mBtnCancelActivityOrderDetails.setText("确认收货");
        mBtnCancelActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(this, R.mipmap.icon_wait_receipt), null, null, null);
        mTabPayActivityOrderDetails.setVisibility(View.VISIBLE);
        // 支付信息
        mLinePayActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvPayTypeActivityOrderDetails.setText(mOrderDetail.getPayType() == 1 ? "支付宝支付" : "微信支付");
        mTvPayDateActivityOrderDetails.setText(mOrderDetail.getPayTime().split(" ")[0]);
        // 付款汇总
        mTvTextPayActivityOrderDetaild.setText("实付款：");
        mTvPayActivityOrderDetails.setText(String.format(
                getString(R.string.string_pay), format.format(mOrderDetail.getStoreList().get(0).getActualPrice())));
        mTvGoodsMmoneyActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getStoreList().get(0).getGoodsPrice())));
        // 优惠券
        mTvDeductionActivityOrderDetails.setText(String.format(getString(R.string.string_sub_pay), format.format(mOrderDetail.getStoreList().get(0).getCouponMoney())));
        // 物流信息
        if (!TextUtils.isEmpty(mOrderDetail.getAcceptStation())) {
            mRelativeExpressActivityOrderDetaild.setVisibility(View.VISIBLE);
            mTvExpressDateActivityOrderDetaild.setVisibility(View.VISIBLE);
            mTvExpressCurrActivityOrderDetaild.setText(mOrderDetail.getAcceptStation());
            mTvExpressDateActivityOrderDetaild.setText(mOrderDetail.getAcceptTime());
            mLine1.setVisibility(View.VISIBLE);
        } else {
            mRelativeExpressActivityOrderDetaild.setVisibility(View.GONE);
            mTvExpressDateActivityOrderDetaild.setVisibility(View.GONE);
            mLine1.setVisibility(View.GONE);
        }
        if (1 == mOrderDetail.getMadeType()) {
            // 定制订单
            mTvCustomInfoActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getMsg());
            mLinearCustomActivityOrderDetails.setVisibility(View.VISIBLE);
        } else {
            mLinearCustomActivityOrderDetails.setVisibility(View.GONE);
        }
        mBtnDeletelActivityOrderDetails.setVisibility(View.GONE);
        mLinearHandleActivityOrderDetails.setVisibility(View.VISIBLE);
    }

    private void initReceiveType(RelativeLayout.LayoutParams params) {
        // 更改蓝条样式
        mTvWaitActivityOrderDetails.setLayoutParams(params);
        mTvPricingActivityOrderDetails.setVisibility(View.GONE);
        mTvRemainingTimeActivityOrderDetails.setVisibility(View.GONE);
        mTvNeedPayActivityOrderDetails.setVisibility(View.GONE);
        mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setText("等待商家发货");
        mBtnPayActivityOrderDetails.setVisibility(View.GONE);
        mBtnCancelActivityOrderDetails.setText("确认收货");
        mBtnCancelActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvWaitActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(this, R.mipmap.icon_wait_receipt), null, null, null);
        mTabPayActivityOrderDetails.setVisibility(View.VISIBLE);
        // 支付信息
        mLinePayActivityOrderDetails.setVisibility(View.VISIBLE);
        mTvPayTypeActivityOrderDetails.setText(mOrderDetail.getPayType() == 1 ? "支付宝支付" : "微信支付");
        mTvPayDateActivityOrderDetails.setText(mOrderDetail.getPayTime().split(" ")[0]);
        // 付款汇总
        mTvTextPayActivityOrderDetaild.setText("实付款：");
        mTvPayActivityOrderDetails.setText(String.format(
                getString(R.string.string_pay), format.format(mOrderDetail.getStoreList().get(0).getActualPrice())));
        mTvGoodsMmoneyActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getStoreList().get(0).getGoodsPrice())));
        // 优惠券
        mTvDeductionActivityOrderDetails.setText(String.format(getString(R.string.string_sub_pay), format.format(mOrderDetail.getStoreList().get(0).getCouponMoney())));
        // 物流信息
        if (!TextUtils.isEmpty(mOrderDetail.getAcceptStation())) {
            mRelativeExpressActivityOrderDetaild.setVisibility(View.VISIBLE);
            mTvExpressDateActivityOrderDetaild.setVisibility(View.VISIBLE);
            mTvExpressCurrActivityOrderDetaild.setText(mOrderDetail.getAcceptStation());
            mTvExpressDateActivityOrderDetaild.setText(mOrderDetail.getAcceptTime());
            mLine1.setVisibility(View.VISIBLE);
        } else {
            mRelativeExpressActivityOrderDetaild.setVisibility(View.GONE);
            mTvExpressDateActivityOrderDetaild.setVisibility(View.GONE);
            mLine1.setVisibility(View.GONE);
        }
        if (1 == mOrderDetail.getMadeType()) {
            // 定制订单
            mTvCustomInfoActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getMsg());
            mLinearCustomActivityOrderDetails.setVisibility(View.VISIBLE);
        } else {
            mLinearCustomActivityOrderDetails.setVisibility(View.GONE);
        }
        mBtnDeletelActivityOrderDetails.setVisibility(View.GONE);
        mLinearHandleActivityOrderDetails.setVisibility(View.GONE);
    }

    private void initPayType(RelativeLayout.LayoutParams params) {
        mLinearHandleActivityOrderDetails.setVisibility(View.VISIBLE);
        if (1 == mOrderDetail.getMadeType()) {
            // 定制订单
            mTvCustomInfoActivityOrderDetails.setText(mOrderDetail.getStoreList().get(0).getMsg());
            if (mOrderDetail.getTotalPrice() <= 0) {
                mTvWaitActivityOrderDetails.setText("等待定价");
                mTvGoodsMmoneyActivityOrderDetails.setText("￥待定");
                mTvPayActivityOrderDetails.setText("￥待定");
                mTvPricingActivityOrderDetails.setVisibility(View.VISIBLE);
                mTvRemainingTimeActivityOrderDetails.setVisibility(View.GONE);
                mTvNeedPayActivityOrderDetails.setVisibility(View.GONE);
                mBtnPayActivityOrderDetails.setVisibility(View.GONE);
                mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.GONE);
            } else {
                mTvWaitActivityOrderDetails.setText("等待付款");
                mTvGoodsMmoneyActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getTotalPrice())));
                mTvPayActivityOrderDetails.setText(String.format(getString(R.string.string_pay), format.format(mOrderDetail.getTotalPrice())));
                mTvPricingActivityOrderDetails.setVisibility(View.GONE);
                mTvRemainingTimeActivityOrderDetails.setVisibility(View.VISIBLE);
                mTvNeedPayActivityOrderDetails.setVisibility(View.VISIBLE);
                mTvNeedPayActivityOrderDetails.setText(String.format(
                        getString(R.string.string_need_pay), format.format(mOrderDetail.getTotalPrice())));
                mBtnPayActivityOrderDetails.setVisibility(View.VISIBLE);
                mBtnPayActivityOrderDetails.setText("去支付");
                mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.GONE);
                startCountDown();
            }
        } else {
            mTvWaitActivityOrderDetails.setText("等待付款");
            mTvPricingActivityOrderDetails.setVisibility(View.GONE);
            mTvRemainingTimeActivityOrderDetails.setVisibility(View.VISIBLE);
            mTvNeedPayActivityOrderDetails.setVisibility(View.VISIBLE);
            mRelativeCouponsInfoActivityOrderDetaild.setVisibility(View.VISIBLE);
            mTvNeedPayActivityOrderDetails.setText(String.format(
                    getString(R.string.string_need_pay), format.format(mOrderDetail.getTotalPrice())));
            mBtnPayActivityOrderDetails.setVisibility(View.VISIBLE);
            mBtnPayActivityOrderDetails.setText("去支付");
            mTvPayActivityOrderDetails.setText(String.format(
                    getString(R.string.string_pay), format.format(mOrderDetail.getActualPrice())));

            startCountDown();
        }
        // 更改蓝条样式
        params.setMargins(0, UIUtils.dip2px(20), 0, 0);
        mTvWaitActivityOrderDetails.setLayoutParams(params);
        mTvTextPayActivityOrderDetaild.setText("需付款：");
        mTvWaitActivityOrderDetails.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(this, R.mipmap.icon_payment), null, null, null);
        mTabPayActivityOrderDetails.setVisibility(View.GONE);
        mLinePayActivityOrderDetails.setVisibility(View.GONE);
        mBtnCancelActivityOrderDetails.setVisibility(View.VISIBLE);
        mBtnCancelActivityOrderDetails.setText("取消订单");
        mRelativeExpressActivityOrderDetaild.setVisibility(View.GONE);
        mLine1.setVisibility(View.GONE);
        mBtnDeletelActivityOrderDetails.setVisibility(View.GONE);
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        showLoadingDialog();
        Observable<StatusCode<String>> cancelObservable = ApiUtils.getApi().cancelOrder(BaseApplication.getToken(), BaseApplication.getUserId(), mOrderDetail.getId());
        HttpUtil.getInstance().toSubscribe(cancelObservable,
                new ProgressSubscriber<String>(this) {
                    @Override
                    protected void _onNext(StatusCode<String> statusCode) {
                        ToastUtils.makeText("订单取消成功");
                        dismissLoadingDialog();
                        getOrderInfo();
                        // 跳转取消
//                        MyOrderActivity.startActivity(OrderDetailsActivity.this, BaseApplication.getUserId(), 4);
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 订单有效期计时器
     */
    private void startCountDown() {
//        new CountDownTimer()
        final long currentTime = mOrderDetail.getExpireTime();
        if (currentTime <= 0) {
            mTvRemainingTimeActivityOrderDetails.setText("订单已取消");
            return;
        } else {
            Observable.interval(0, 1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new Function<Long, Long>() {
                        @Override
                        public Long apply(Long aLong) throws Exception {
                            return currentTime - (aLong * 1000);
                        }
                    })
                    .take(currentTime)
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            mTimerDisposable = d;
                        }

                        @Override
                        public void onNext(Long value) {
                            long house = value / (1000 * 60 * 60);
                            long min = (value - house * 60 * 60 * 1000) / (1000 * 60);
                            long sec = (value - house * 60 * 60 * 1000 - min * 60 * 1000) / 1000;
                            if (house > 0 || min > 0) {
                                mTvRemainingTimeActivityOrderDetails.setText(
                                        String.format(getString(R.string.string_count_down), house, min));
                            } else {
                                mTvRemainingTimeActivityOrderDetails.setText("剩余1分钟");
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                            mTvRemainingTimeActivityOrderDetails.setText("订单已取消");
                            MyOrderActivity.startActivity(OrderDetailsActivity.this, BaseApplication.getUserId(), 4);
                        }
                    });
        }
    }
}
